<template>
<div class="v-flex-layout article-editor">
  <div class="is-auto article-info-warp">
    <article-info :editing-article="editingArticle" ref="articleInfo" @on-infoChange="infoChangeHandle"></article-info> 
  </div>
  <div class="is-auto ctrl-warp clearfix">
    <span class="ctrl-btn" @click="articleUpdate" title="保存">
      <el-badge is-dot :hidden="!contentChange">
        <em class="el-icon el-icon-upload" ></em>
      </el-badge>
    </span>
    
    <span class="ctrl-btn" title="图片列表" >
      <el-badge :value="articleImgs.length" > 
         <el-popover
          placement="bottom"
          width="400"
          trigger="click">
          <div >
            <my-flex :column="4" wrap="wrap" border>
              <my-flex-item class="img-item-warp" shadow="hover" >
                <!-- <div class="add-img"> </div> -->
                <el-upload
                  class="add-img"
                  ref="upload" 
                  action=""
                  accept=".jpg,.png,.bmp,.jpeg,.gif"
                  :show-file-list="false"
                  :http-request="fileUploadFn" 
                >  
                  <em  slot="trigger" class="el-icon el-icon-plus"></em>
                </el-upload>
              </my-flex-item>  
              <my-flex-item class="img-item-warp" v-for="(item, index) in articleImgs" :key="`img_${index}`" shadow="hover" >
                <div class="inner" 
                @click="imgTextInsertToMd(item)"
                :title="item.split('@')[0]"
                :style="{'background-image': `url('${serverHost}${item.split('@')[1].replace(/\\/g, '/')}')`}"
                ></div>
                
              </my-flex-item>
            </my-flex>
          </div>
          <em class="el-icon el-icon-picture-outline"  slot="reference"></em>
          
        </el-popover>
      </el-badge>
    </span>  
  </div> 
  <!-- <div class="is-auto"> 
    {{contentText}}
  </div> -->
  <div class="is-flex editor-warp">
    <div class="inner" style="padding-left: 10px;">
      <md-editor ref="mdEditor" v-model="contentText" @on-imgUploaded="mdImgUploadHandle"></md-editor>
    </div>
  </div>
</div>
</template>
<style lang="scss" scoped>
.article-editor{
  box-sizing: border-box;
  height: 100%; 
  .ctrl-warp{
    padding: 3px;
    border-top: 1px solid rgba(0, 0, 0, 0.09);
    border-bottom: 1px solid rgba(0, 0, 0, 0.09);
    .ctrl-btn{
      float: left;
      margin-right:5px;
      cursor:pointer;
      color: #a6a6a6;
      font-size: 20px
    }
  }
}

.img-item-warp{
  padding-top: 20%;
  .inner{
    width: 100%;
    height: 100%;
    background: no-repeat;
    background-position: center center;
    background-size: contain;
  }
  .add-img{
    display: flex;
    width: 100%;
    height: 100%;
    flex-flow: row nowrap;
    align-items: center;
    justify-content: center;
    .el-icon{
      font-size: 30px;
    }
  }
}
</style>
<script>
import {SERVER_HOST} from '@/constant'
import {FILE_UPLOAD} from '$my/code/api/file'
import {normalUpload} from '@/helper/updownload'
import ArticleInfo from '@/components/markdown/article-info'
import MdEditor from '@/components/md-editor/index'
import mdArticle from '$my/code/mixin/md-article'
export default {
  mixins: [mdArticle],
  components: {
    ArticleInfo,
    MdEditor
  },
  props: {
    editingArticle: {
      type: Object
    }
  },
  data() {
    return {
      articleTitle: '',
      articleTags: [],
      articleImgs: [],
      contentText: '',
      serverHost: SERVER_HOST
    }
  },
  computed: {
    contentChange() {
      if (
        this.articleTitle !== this.editingArticle.title || 
        this.contentText !== this.editingArticle.mdText || 
        this.articleTags.join(',') !== this.editingArticle.tags.map((item) => { return item.id }).join(',') || 
        this.articleImgs.join(',') !== this.editingArticle.imgs.join(',')
      ) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    fileUploadFn(target) {  
      normalUpload(target.file, FILE_UPLOAD).then((res) => {
        this.articleImgs.push(res.id) 
        this.imgTextInsertToMd(res.id)
      })
    },
    previewImgClick(id) {
      console.log('preview', id)
    },
    imgTextInsertToMd(id) {
      const imgStr = `![${id.split('@')[0]}](${SERVER_HOST}${id.split('@')[1].replace(/\\/g, '/')})`
      this.$refs.mdEditor.insertContent(imgStr)
    },
    infoChangeHandle(newInfo) { 
      this.articleTitle = newInfo.title
      this.articleTags = newInfo.tags.map((item) => { return item.id })
    },
    mdImgUploadHandle(uploadFile) {
      this.articleImgs.push(uploadFile.id)
    },
    articleUpdate() { 
      const params = {
        id: this.editingArticle.id,
        mdText: this.contentText,
        mdContent: this.$refs.mdEditor.getContent(),
        title: this.articleTitle,
        tags: this.articleTags,
        imgs: this.articleImgs
      }  
      this.updateMdArticle({
        data: params
      }).then((res) => {
        console.log('update', res)
        this.$emit('on-itemSave', res)
      }) 
    }
  },
  created() {
    this.contentText = this.editingArticle.mdText
    this.articleTitle = this.editingArticle.title
    this.articleTags = this.editingArticle.tags.map((item) => { return item.id })
    this.articleImgs = JSON.parse(JSON.stringify(this.editingArticle.imgs))

  },
  mounted() {
    this.intervalTimer = setInterval(() => {
      if (this.contentChange) {
        this.articleUpdate()
      }
    }, 10 * 1000)
  },
  
  beforeDestroy() {
    this.articleUpdate()
    clearInterval(this.intervalTimer)
  }
}
</script>